'''
# -*- coding:utf-8 -*-
# @Project: DevOps_api
# @Date: 2023/3/24 - 14:58
# @Author: ysg
# @Describe: 

files_handle.py
'''

import os
from libs.connect_ssh.devops_ssh import do_ssh
from APS.views import insert_cron_job


def write_file(localpath, mode, info):
    with open(localpath, mode)as fw:
        for line in info:
            fw.write(line)


def upload_handle(info, file_name, host_ip, req):
    '''
    上传监控脚本时，创建对应的定时任务
    :param info:
    :param file_name:
    :param host_ip:
    :param req:
    :return:
    '''
    load = os.path.join(r'./DevOps_api/DevOps_api/media/upload', file_name)
    write_file(load, 'wb', info)
    ssh, sftp = do_ssh(host_ip)
    # 上传监控脚本
    py_path = f'/ysg/monitorpy/{info.name}'
    sftp.put(localpath=load, remotepath=py_path)
    ssh.exec_command(f'chmod +x {py_path}')  # 添加可执行权限，运行脚本
    # 建立对应脚本的定时任务
    insert_cron_job(file_name, req)


def delete_handle(host_ip, file_name):
    '''
    删除监控脚本时，删除对应的监控脚本
    :param host_ip:
    :param file_name:
    :return:
    '''
    ssh, sftp = do_ssh(host_ip)
    ssh.exec_command(f'rm -fr /ysg/monitorpy/{file_name}')  # 添加可执行权限，运行脚本


def get_linux_result(ssh, commands):
    stdin, stdout, stderr = ssh.exec_command(commands)
    res, err = stdout.read().decode(), stderr.read().decode()
    result = res if res else err
    return result


def for_push_file(file_ip, file_path, localpath):
    '''
    循环遍历 IP 上传文件
    :param file_ip:
    :param file_path:
    :param localpath:
    :return:
    '''
    textarea = """"""
    for ip in file_ip:
        ssh, sftp = do_ssh(ip)
        result = get_linux_result(ssh, f'ls -l {file_path}')
        if 'No such file or directory' in result:
            path = file_path.split('/')[:-1]
            linux_path = '/'.join(path)
            ssh.exec_command(f'mkdir -p {linux_path}')
        # put 后续可能会加 celery 异步任务
        sftp.put(localpath, file_path)
        result = get_linux_result(ssh, f'md5sum {file_path}')
        textarea += result.replace('\n', '', -1) + '  ----  ' + ip + '\n'
    return textarea
